package certs

import (
	"context"
	"net"
	"testing"

	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	bkeinit "gopkg.openfuyao.cn/bkecommon/cluster/initialize"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"

	bkev1beta1 "gopkg.openfuyao.cn/cluster-api-provider-bke/api/v1beta1"
)

var bkeCluster = &bkev1beta1.BKECluster{
	TypeMeta: metav1.TypeMeta{
		Kind:       "BKECluster",
		APIVersion: "bke.bocloud.com/v1beta1",
	},
	ObjectMeta: metav1.ObjectMeta{
		Name:      "test",
		Namespace: "default",
		UID:       "test",
	},
	Spec: bkev1beta1.BKEClusterSpec{
		ClusterConfig: &confv1beta1.BKEConfig{
			Cluster: confv1beta1.Cluster{
				ControlPlane: confv1beta1.ControlPlane{
					Etcd: &confv1beta1.Etcd{
						ServerCertSANs: []string{"1.1.1.1", "abc.com"},
					},
					APIServer: &confv1beta1.APIServer{
						CertSANs: []string{"2.2.2.2", "def.com"},
					},
				},
			},
		},
	},
}

func TestGenerateCert(t *testing.T) {
	// create a client
	c, err := client.New(ctrl.GetConfigOrDie(), client.Options{})
	if err != nil {
		t.Fatal(err)
	}
	cfg := bkeinit.BkeConfig(*bkeCluster.Spec.ClusterConfig)
	bkeinit.SetDefaultBKEConfig(&cfg)

	generator := NewKubernetesCertGenerator(context.TODO(), c, bkeCluster)
	if err := generator.LookUpOrGenerate(); err != nil {
		t.Fatal(err)
	}
	if err := generator.VerifyCertificateSans(); err != nil {
		t.Fatal(err)
	}
	if err := generator.VerifyExpirationTime(); err != nil {
		t.Fatal(err)
	}
}

func TestGenerateKubeconfig(t *testing.T) {
	c, err := client.New(ctrl.GetConfigOrDie(), client.Options{})
	if err != nil {
		t.Fatal(err)
	}
	cfg := bkeinit.BkeConfig(*bkeCluster.Spec.ClusterConfig)
	bkeinit.SetDefaultBKEConfig(&cfg)

	generator := NewKubernetesCertGenerator(context.TODO(), c, bkeCluster)
	generator.ConfigKubeConfig(net.JoinHostPort("3.3.3.3", "6443"))
	if err := generator.LookUpOrGenerate(); err != nil {
		t.Fatal(err)
	}
}
